<template>
  <!-- 主界面 -->
  <el-card v-if="!smallWindowStore.showSmallWindow" class="timer-container">
    <!-- 头部 -->
    <div class="header">
      <h2>408 科目训练</h2>
      <el-select
          class="subject-select"
          v-model="selectedSubject"
          placeholder="选择科目"
          size="large"
          style="width: 240px">
        <el-option
            v-for="subject in subjects"
            :key="subject.name"
            :label="subject.name"
            :value="subject.name"/>
      </el-select>
    </div>

    <!-- 标题 -->
    <div class="title">
      <h1>训练计时</h1>
    </div>

    <!-- 时间 -->
    <div class="timer-display">
      <p class="time-text">{{ formattedTime }}</p>
    </div>

    <div class="controls">
      <button @click="startTimer" :disabled="smallWindowStore.isRunning">开始</button>
      <button @click="pauseTimer" :disabled="!smallWindowStore.isRunning">暂停</button>
      <button @click="resetTimer" :disabled="smallWindowStore.clockTime === 0">结束</button>
      <button @click="clearTimer">重置</button>
      <!-- <button @click="showLearningRecords">学习记录</button> -->
    </div>

    <div class="footer">
      <button class="minimize-btn" @click="minimizeWindow">返回首页 / 最小化</button>
    </div>
  </el-card>

  <!-- 弹窗 -->
  <el-dialog :visible.sync="isLearningRecordsDialogVisible" title="我的学习记录">
    <div ref="learningRecordsChart" style="width: 600px; height: 400px;"></div>
  </el-dialog>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { useSmallWindowStore } from '@/stores/smallWindow';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const smallWindowStore = useSmallWindowStore();
const router = useRouter();

// 初始化
const subjects = [
  { name: '数据结构', id: 1 },
  { name: '计算机网络', id: 2 },
  { name: '计算机组成原理', id: 3 },
  { name: '操作系统', id: 4 }
];
const selectedSubject = ref(subjects[0].name); // 默认选择第一个科目

// 计时格式化
const formattedTime = computed(() => {
  const minutes = Math.floor(smallWindowStore.clockTime / 60);
  const seconds = smallWindowStore.clockTime % 60;
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
});

// 科目名称到科目 ID 的映射
function getSubjectIdByName(subjectName) {
  const subject = subjects.find(s => s.name === subjectName);
  return subject ? subject.id : null;
}

// 计时控制
const startTimer = () => {
  smallWindowStore.startTimer();
};

const pauseTimer = () => {
  smallWindowStore.pauseTimer();
};

const resetTimer = async () => {
  console.log(`结束：${selectedSubject.value}，用时 ${formattedTime.value}`);

  // 计算学习时长（单位：秒）
  const duration = smallWindowStore.clockTime;

  // 获取科目 ID
  const subjectId = getSubjectIdByName(selectedSubject.value);

  // 构造发送到后端的数据
  const learnDTO = {
    duration: duration,
    subject: subjectId // 发送科目 ID
  };

  // 发送 POST 请求到后端
  try {
    const response = await axios.post('http://localhost:8080/learn/record', learnDTO, {
      headers: {
          Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
        },
    });

    if (response.data.message==="success") {
        ElMessage.success('学习记录已成功保存到数据库')
      console.log('学习记录已成功保存到数据库');
    } else {
      ElMessage.error('保存学习记录失败：' + response.data.message)
      console.error('保存学习记录失败：', response.data.message);
    }
  } catch (error) {
    console.error('请求失败：', error);
  }

  // 重置计时器
  smallWindowStore.resetTimer();
};

const clearTimer = () => {
  smallWindowStore.clockTime = 0;
};

// 最小化窗口并跳转到首页
const minimizeWindow = () => {
  smallWindowStore.showSmallWindow = true;
  router.push('/home');
};

// 弹窗显示状态
const isLearningRecordsDialogVisible = ref(false);

// 初始化 ECharts 图表
const learningRecordsChart = ref(null);
let myChart = null;

onMounted(() => {
  if (learningRecordsChart.value) {
    myChart = echarts.init(learningRecordsChart.value);
  }
});

// 获取学习记录数据
const fetchLearningRecords = async () => {
  try {
    const token = smallWindowStore.token; // 假设 token 已经存储在 store 中
    const response = await axios.get('http://localhost:8080/learn/selectByUserId', {
      params: {
        userId: 1 // 假设用户 ID 是 1，可以根据实际情况获取
      },
       headers: {
          Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
        },
    });

    const records = response.data.data; // 假设后端返回的数据结构是 { data: [Learn] }
    console.log(records)
    const subjects = records.map(record => record.subject);
    const durations = records.map(record => record.duration);

    const option = {
      title: {
        text: '我的学习记录'
      },
      tooltip: {},
      legend: {
        data: ['学习时长']
      },
      xAxis: {
        data: subjects
      },
      yAxis: {},
      series: [
        {
          name: '学习时长',
          type: 'bar',
          data: durations
        }
      ]
    };

    myChart.setOption(option);
  } catch (error) {
    console.error('获取学习记录失败：', error);
  }
};

// 显示学习记录弹窗
const showLearningRecords = () => {
  isLearningRecordsDialogVisible.value = true;
  fetchLearningRecords();
};
</script>

<style lang="scss" scoped>
.timer-container {
  @include hold(99, 99);

  background-color: $global-background-color;
  color: $global-font-color;
  text-align: center;
  font-family: 'Segoe UI', sans-serif;
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  font-size: 22px;
  margin: 0;
}

.subject-select {
  font-size: 16px;
  padding: 5px 10px;
}

/* 标题 */
.title {
  margin-top: 20px;
}

.title h1 {
  font-size: 32px;
  font-weight: bold;
  margin: 20px 0;
}

/* 时间显示 */
.timer-display {
  margin: 20px 0;
}

.time-text {
  font-size: 120px;
  font-weight: bold;
}

/* 控制按钮 */
.controls {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.controls button {
  width: 120px;
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #409eff;
  color: white;
}

.controls button:disabled {
  background-color: #bbb;
  cursor: not-allowed;
}

.footer {
  margin-top: 30px;
}

.minimize-btn {
  background-color: #f56c6c;
  padding: 8px 20px;
  border-radius: 8px;
  border: none;
  font-size: 16px;
  color: white;
  cursor: pointer;
}
</style>